﻿// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkID=397704
// To debug code on page load in Ripple or on Android devices/emulators: launch your app, set breakpoints, 
// and then run "window.location.reload()" in the JavaScript Console.

var deviceReadyDeferred = $.Deferred();
var jqmReadyDeferred = $.Deferred();
var gpsDeferred = $.Deferred();
var gpsPosition = null;
var initCache = $.Deferred();

(function () {
    "use strict";

    document.addEventListener('deviceready', onDeviceReady.bind(this), false);

    function onDeviceReady() {
        // Handle the Cordova pause and resume events
        document.addEventListener('pause', onPause.bind(this), false);
        document.addEventListener('resume', onResume.bind(this), false);

        // TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.



        
        //$(function () {
        //    alert("activate fast click");
        //    FastClick.attach(document.body);
        //    $.mobile.defaultHomeScroll = 0;
        //});



        //$(function () {
        //    alert("here we go.....  scroll");
        //    $.mobile.defaultHomeScroll = 0;
        //});




        // Global Error Handler
        window.onerror = function (msg, url, line, col, error) {
            // Save error msg to session storage and load error page
            //alert("Msg: " + msg);
            //alert("url: " + url);
            //alert("line: " + line);
            //alert("col: " + col);
            //alert("error: " + error);
            //alert("page: " + GetQueryString("CurrentPage"));

            // Instantiate new error object and load with values, then go to error page
            var e = new Error();
            e.message = msg;
            e.url = url;
            e.line = line;
            e.col = col;
            e.error = error;
            GoToErrorPage(GetQueryString("CurrentPage"), e);
        };

        // IOS Only functions
        if (navigator.userAgent.match(/iphone|ipad|ipod/i)) {

            // Allow screen rotate IOS
            window.shouldRotateToOrientation = function (degrees) {
                return true;
            }

            // Drop app down below IOS status bar and make background black
            StatusBar.overlaysWebView(false);
            StatusBar.backgroundColorByName('black');
        }
        
        // Don't use and drive notification
        navigator.notification.alert(
            stringConstants.disclaimerMessage,  // message
            null,                               // callback
            'Warning',                          // title
            'Agree'                             // buttonName
        );

        // Notification window
       // navigator.notification.confirm(
       //    'You are the winner!', // message
       //     onConfirm,            // callback to invoke with index of button pressed
       //    'Game Over',           // title
       //    ['Restart', 'Exit']         // buttonLabels
       //);


        // Allow for OS font sizing over ride / Accessability 
        //if (window.MobileAccessibility) {
        //    window.MobileAccessibility.usePreferredTextZoom(true);
        //}










        // Device on ready complete
        //var msgXX = "DEVICE ON READY START";
        //alert(msgXX.toLowerCase());
        deviceReadyDeferred.resolve();


        //alert("Get GPS to flip'en work............");
        if (navigator.geolocation) {
            //navigator.geolocation.getCurrentPosition(success, fail, { maximumAge: 8000, timeout: 10000, enableHighAccuracy: true });
            SaveQueryString("GPS", "true");
        }
        gpsDeferred.resolve();
    };


    // process the confirmation dialog result
    //function onConfirm(buttonIndex) {
    //    alert('You selected button ' + buttonIndex);
    //}



    function onPause() {
        // TODO: This application has been suspended. Save application state here.
    };

    function onResume() {
        // TODO: This application has been reactivated. Restore application state here.
    };

    function success(pos) {
        // Location found, show map with these coordinates
        //alert("Success GPS: " + pos.coords.latitude + " " + pos.coords.longitude);
        SaveQueryString("GPS", "true");
        gpsPosition = pos.coords.latitude + ',' + pos.coords.longitude;
        gpsDeferred.resolve();

    };
    function fail(error) {
        DeleteQueryString("GPS");
        gpsDeferred.resolve();
    };


})();

//function onSuccess(position) {
//    alert("GPS STARTING");
//    //var xxx = 'Latitude: ' + position.coords.latitude + '<br />' +
//    //                    'Longitude: ' + position.coords.longitude + '<br />' +
//    //                    'Altitude: ' + position.coords.altitude + '<br />' +
//    //                    'Accuracy: ' + position.coords.accuracy + '<br />' +
//    //                    'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '<br />' +
//    //                    'Heading: ' + position.coords.heading + '<br />' +
//    //                    'Speed: ' + position.coords.speed + '<br />' +
//    //                    'Timestamp: ' + position.timestamp + '<br />';
//    //alert("GPS: " + xxx);
//    gpsPosition = position.coords.latitude + ',' + position.coords.longitude;
//    gpsDeferred.resolve();
//}

//// onError Callback receives a PositionError object
//function onError(error) {
//    alert('NO GPScode: ' + error);       //      'message: ' + error.message + '\n');
//    // Do nothing on GPS error 
//    gpsDeferred.resolve();
//}


$(document).on('pageinit', '#loading', function (e) {
    if (e.handled != true) {
        try {

            //alert("PAGEINIT START");

            // JQM Page Init complete
            jqmReadyDeferred.resolve();

        } catch (e) {
            GoToErrorPage(GetQueryString("CurrentPage"), e);
        }

        e.handled = true;
    }
});

// When all events are complete ( device On Ready, and JQM Page Init, get gps data ) run initialize function
$.when(deviceReadyDeferred, jqmReadyDeferred, gpsDeferred).then(doWhenBothFrameworksLoaded);
//$.when(deviceReadyDeferred, jqmReadyDeferred).then(doWhenBothFrameworksLoaded);

function doWhenBothFrameworksLoaded() {
    try {
        //alert("FINAL START");

        // Detect if communcations exist, if not go to error
        if (!isNetworkConnected()) {
            var e = new Error();
            e.message = "No Network Detected";
            GoToErrorPage(GetQueryString("CurrentPage"), e);
        }

        // Get Device Information and save to session storage
        //alert("YOUI DID IT: " + device.uuid);
        SaveQueryString("platform", device.platform);
        SaveQueryString("uuid", device.uuid);

        // Get bearer token from Authorization Server and store in session storage
        
        // Cache Manager Initialize
        //InitCache();
        Startup(gpsPosition);
        //alert("RETURN FROM INIT CACHE.........");
        
        // When Cache manager startup complete establish session and go to main page
        $.when(initCache).then(StartSession);

    } catch (e) {
        GoToErrorPage(GetQueryString("CurrentPage"), e);
    }
}

function StartSession() {
    // Add key to indicate session created
    sessionStorage.setItem('SESSION', 'True');

    //alert("SESSION CREATED");
    $.mobile.changePage("index.html", { changeHash: true });
}


$(document).on("pagechange", function (e, data) {
    if (e.handled != true) {
        SaveQueryString("CurrentPage", data.toPage[0].id);
        e.handled = true;
    }
});

$(document).on("pagebeforechange", function (e, ob) {
    if (e.handled != true) {
        //alert("page change");
        if (ob.toPage && (typeof ob.toPage === "string") && ob.toPage.indexOf('loading.html') >= 0) {
            //alert("blocking the back");
            navigator.app.exitApp();
            e.preventDefault();
        }
        e.handled = true;
    }
});



// Full screen code
$(document).on("pagecontainertransition", function () {

    //alert("height: " + $(window).height());
    //alert("width: " + $(window).width());
    

    FullScreenAdjust();
});

$(window).on("resize", function () {

    //alert("height: " + $(window).height());
    //alert("width: " + $(window).width());
    
    FullScreenAdjust();
});

$(window).on("orientationchange", function () {

    //alert("height: " + $(window).height());
    //alert("width: " + $(window).width());
    
    FullScreenAdjust();
});


function FullScreenAdjust() {
    var screen = $.mobile.getScreenHeight(),
        header = $(".ui-header").hasClass("ui-header-fixed") ? $(".ui-header").outerHeight() - 1 : $(".ui-header").outerHeight(),
        footer = $(".ui-footer").hasClass("ui-footer-fixed") ? $(".ui-footer").outerHeight() - 1 : $(".ui-footer").outerHeight(),
        contentCurrent = $(".ui-content").outerHeight() - $(".ui-content").height(),
        content = screen - header - footer - contentCurrent;
        content = screen - header - contentCurrent;
    $(".ui-content").height(content);


    $('#mainmenu').css('margin-top', ($(window).height() - $('[data-role=header]').height() - $('[data-role=footer]').height() - $('#mainmenu').outerHeight()) / 2);




    //$('#mainmenu').css('margin-top', ($(window).height() - $('[data-role=header]').height() - $('[data-role=footer]').height() - $('#index-content').outerHeight()) / 2);

}